package com.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 处理客户端连接的事件
 */
class ServerHandler extends ChannelInitializer {

    @Override
    protected void initChannel(Channel channel) throws Exception {
        System.out.println("客户端来了没?");
        channel.pipeline().addLast(new StringDecoder()); //解码器:接收
        channel.pipeline().addLast(new StringEncoder()); //编码器：发送
        channel.pipeline().addLast(new RecvMessage());
    }
}

/**
 * 接收消息
 */
class RecvMessage extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        super.channelRead(ctx, msg);
        System.out.println("收到了消息:"+msg);
        //ctx.channel().writeAndFlush("我是Netty服务器返回的"); //发送给客户端
        ctx.channel().close();
    }




}


public class NettyServer {

    public static void main(String[] args) throws InterruptedException {
         //1.服务器装配器（引导器)
        ServerBootstrap serverBootstrap = new ServerBootstrap();
         //2.创建事件管理组(服务器要两个事件组 a.管连接(前台) b.管具体操作(服务员)
        EventLoopGroup  bossGroup = new NioEventLoopGroup();
        EventLoopGroup  workGroup = new NioEventLoopGroup();
        serverBootstrap.group(bossGroup,workGroup);
        //3.设置通道类型(使用用阻塞还是异步)
        serverBootstrap.channel(NioServerSocketChannel.class);
        //4.设置监听端口
        //serverBootstrap.bind(9090);
        //5.设置参数
        //6.写事件(装配流水线)
        //serverBootstrap.handler() //服务器自己初始化的时候要执行的代码

        //当有客户端连接的时候，要执行的事件
        serverBootstrap.childHandler(new ServerHandler());
        //7.启动并绑定端口
        ChannelFuture cf = serverBootstrap.bind(9090).sync();
        //8.等待关闭
        cf.channel().closeFuture().sync();
        //9.关闭事件
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();








    }
}
